package com.pig4cloud.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.convert.ConverterRegistry;
import cn.hutool.json.JSONUtil;
import com.pig4cloud.config.RedisConfig;
import com.pig4cloud.core.domain.AjaxResult;
import com.pig4cloud.domain.SysUser;
import com.pig4cloud.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("list")
    public AjaxResult findAll(){
        List<SysUser> list = sysUserService.findAll();
        redisTemplate.opsForValue().set("user:",list,30, TimeUnit.MINUTES);
        return AjaxResult.success(list);
    }

    /**
     * 将对象装换成JSON格式存储到redis中
     * 再将redis中取到的JSON格式装换成User对象
     * @return
     */
    @GetMapping("stringRedisList")
    public Object stringRedisList(){
        SysUser sysUser = sysUserService.findAll().get(0);
        String s = JSONUtil.toJsonStr(sysUser);
        stringRedisTemplate.opsForValue().set("redis:json",s,30,TimeUnit.MINUTES);
        //
        redisTemplate.opsForValue().set("redis:object",sysUser,30,TimeUnit.MINUTES);
        Map<String,Object> map = new HashMap<>();
        SysUser sysUser1 = JSONUtil.toBean(stringRedisTemplate.opsForValue().get("redis:json"), SysUser.class);
        map.put("json",sysUser1);
        map.put("object",redisTemplate.opsForValue().get("redis:object"));
        return map;
    }
    @GetMapping("redisList")
    public Object redisList(){
        Object o = redisTemplate.opsForValue().get("user:");
        return o;

    }


}
